import React from "react";
import { Dayjs } from "dayjs";
import RcPicker from "rc-picker";
import locale from "rc-picker/es/locale/zh_CN";
import generateConfig from "rc-picker/es/generate/dayjs";
import type { TimePickerProps } from "./type";
import { Time as TimeIcon, Dateclear as DataClearIcon } from "@ct0/icons";

const TimePicker = ({
  value,
  defaultValue,
  onChange,
  disabled,
  allowClear = true,
  placeholder = "请选择时间",
  style,
  className,
  format = "HH:mm:ss",
  showNow = false,
}: TimePickerProps) => {
  const handleChange = (time: Dayjs | null, timeString?: string) => {
    onChange?.(time, timeString);
  };

  const [showHour, showMinute, showSecond] = initPanel(format);

  return (
    <RcPicker<Dayjs>
      prefixCls="ct0-time-picker"
      picker="time"
      generateConfig={generateConfig}
      locale={locale}
      disabled={disabled}
      allowClear={allowClear}
      placeholder={placeholder}
      value={value}
      defaultValue={defaultValue ?? undefined}
      onChange={handleChange}
      getPopupContainer={(node: any) => node.parentNode}
      clearIcon={<DataClearIcon />}
      suffixIcon={<TimeIcon />}
      className={className}
      style={style}
      format={format}
      showNow={showNow}
      showHour={showHour}
      showMinute={showMinute}
      showSecond={showSecond}
      role="ct0-time-picker"
    />
  );
};

export default TimePicker;

/**
 * 浮层中的列会随着 format 变化，当略去 format 中的某部分时，浮层中对应的列也会消失。
 * @param {string} format
 * @example
 * const [showHour, showMinute, showSecond] = initPanel("HH:mm:ss");
 * @example 返回值
 * initPanel("HH:mm:ss");  //return [true, true, true]
 * initPanel("mm:ss");  //return [false, true, true]
 * @returns {Array<boolean>} 返回时、分、秒是否显示标记的数组
 */
export function initPanel(format: string): Array<boolean> {
  const template = typeof format === "string" ? format : "HH:mm:ss";
  return [
    template.includes("H") || template.includes("h"),
    template.includes("m"),
    template.includes("s"),
  ];
}
